import type { ApiRes, ChannelItem, ChannelRes } from '@/type'
import { getToken, http } from '@/utils'
import { makeAutoObservable, computed } from 'mobx'
import { differenceBy } from 'lodash'
import { rootStore } from './index'
class ChannelStore {
  channelData: ChannelRes // 已选频道
  allChannelData: ChannelRes // 所有频道
  activeKey: Number // 频道激活key
  constructor() {
    makeAutoObservable(this, {
      choseChannelList: computed,
    })
    this.channelData = { channels: [] } as ChannelRes
    this.allChannelData = { channels: [] } as ChannelRes
    this.activeKey = 0
  }
  // 通过计算属性计算可选列表
  get choseChannelList() {
    // 所有频道减去已选频道
    // 数组筛选: 遍历所有频道列表 然后拿到每一项的id去已选频道中匹配
    // 如果匹配了 代表当前项不能出现在可选列表中 如果没匹配是符合条件的
    return differenceBy(
      this.allChannelData.channels,
      this.channelData.channels,
      'id'
    )
  }
  // 获取channel列表
  getChannelList = async () => {
    const res = await http.get<ApiRes<ChannelRes>>('/user/channels')
    this.channelData = res.data.data
  }
  // 获取所有频道列表
  getAllChannelList = async () => {
    const res = await http.get<ApiRes<ChannelRes>>('/channels')
    this.allChannelData = res.data.data
  }
  // 切换activeKey
  switchActiveKey(key: number) {
    this.activeKey = key
    // 重新执行获取最新的文章列表
    rootStore.articleStore.refreshList(key)
  }
  // 删除我的频道
  delMyChannel = async (id: number) => {
    // 如果是登录状态 调用接口  非登录 删本地
    if (getToken()?.token) {
      await http.delete('/user/channels', {
        data: {
          channels: [id],
        },
      })
      this.getChannelList()
    } else {
      // 找到要删除项的下标值
      const index = this.channelData.channels.findIndex(
        (item) => item.id === id
      )
      // 删除操作
      this.channelData.channels.splice(index, 1)
    }
  }
  // 添加我的频道
  addMyChannel = async (channel: ChannelItem) => {
    // 如果是登录状态 调用接口  非登录 操作本地
    if (getToken()?.token) {
      await http.patch('/user/channels', {
        channels: [
          {
            id: channel.id,
            seq: this.channelData.channels.length,
          },
        ],
      })
      this.getChannelList()
    } else {
      this.channelData.channels.push(channel)
    }
  }
}

export default ChannelStore
